//
//  simplest_eagl.m
//  QH_Simplest_EAGL_Demo
//
//  Created by Anakin chen on 2021/2/17.
//

#import "simplest_eagl.h"

@implementation simplest_eagl

+ (instancetype)createWith:(UIView *)preview {
    simplest_eagl *this = [simplest_eagl new];
    this.preview = preview;
    [this p_setup];
    return this;
}

- (void)captureOutput {
    if (dispatch_semaphore_wait(_frameRenderingSemaphore, DISPATCH_TIME_NOW) != 0) {
        return;
    }
    dispatch_async(_videoQueue, ^{
        // 如果是使用 CIContext， 这里不需要 setCurrentContext，可能它内部执行了
        if ([EAGLContext currentContext] != self.eaglContext) {
            [EAGLContext setCurrentContext:self.eaglContext];
//            NSLog(@"setCurrentContext-%@", [NSThread currentThread]);
        }
        [self p_processVideoSampleBuffer];
        dispatch_semaphore_signal(self.frameRenderingSemaphore);
    });
}

#pragma mark - Pirvate

- (void)p_setup {
    _eaglContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    
    _videoQueue = dispatch_queue_create("com.eagl.render", NULL);
    _frameRenderingSemaphore = dispatch_semaphore_create(1);
    
//    dispatch_sync(_videoQueue, ^{
//        [EAGLContext setCurrentContext:self.eaglContext];
//    });
}

- (void)p_processVideoSampleBuffer {
}

@end
